package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.CompanyForumTopicAnswerListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseSingleChoiceDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.SimpleDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.RequestManager;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompanyForumAnswer;
import com.isunland.managesystem.entity.CompanyForumAnswer.actualObject;
import com.isunland.managesystem.entity.CompanyForumTopic;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.FileNetWorkUtil;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.widget.RoundImageView;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.http.Header;

/**
 * 话题回复列表
 *
 * @author wu
 */
public class CompanyForumTopicAnswerListFragment extends BaseListFragment
    implements OnClickListener {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  public static final int RESULT_EDIT = 6;
  protected static final String TAG = "CompanyForumTopicAnswerListFragment";
  private static final int REQUEST_CHOOSE = 0;
  private static final int REQUEST_REPLY = 0; // 话题回复
  private static final int REQUEST_MESSAGE = 1;
  private static final int REQUEST_DELETE = 2;
  private static final int REQUEST_TOPIC_ANSWER = 2; // 话题的回复
  private static final int REQUEST_TOPIC_ANSWER_REPLY = 3;// 对应目标数据的回复
  private static final int REQUEST_SHOW = 4;
  private static final int REQUEST_DOWNLOAD = 5;
  private static final String[][] MIME_MapTable = {
      // {后缀名，MIME类型}
      { ".3gp", "video/3gpp" }, { ".apk", "application/vnd.android.package-archive" },
      { ".asf", "video/x-ms-asf" }, { ".avi", "video/x-msvideo" },
      { ".bin", "application/octet-stream" }, { ".bmp", "image/bmp" }, { ".c", "text/plain" },
      { ".class", "application/octet-stream" }, { ".conf", "text/plain" }, { ".cpp", "text/plain" },
      { ".doc", "application/msword" },
      { ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
      { ".xls", "application/vnd.ms-excel" },
      { ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
      { ".exe", "application/octet-stream" }, { ".gif", "image/gif" },
      { ".gtar", "application/x-gtar" }, { ".gz", "application/x-gzip" }, { ".h", "text/plain" },
      { ".htm", "text/html" }, { ".html", "text/html" }, { ".jar", "application/java-archive" },
      { ".java", "text/plain" }, { ".jpeg", "image/jpeg" }, { ".jpg", "image/jpeg" },
      { ".js", "application/x-javascript" }, { ".log", "text/plain" },
      { ".m3u", "audio/x-mpegurl" }, { ".m4a", "audio/mp4a-latm" }, { ".m4b", "audio/mp4a-latm" },
      { ".m4p", "audio/mp4a-latm" }, { ".m4u", "video/vnd.mpegurl" }, { ".m4v", "video/x-m4v" },
      { ".mov", "video/quicktime" }, { ".mp2", "audio/x-mpeg" }, { ".mp3", "audio/x-mpeg" },
      { ".mp4", "video/mp4" }, { ".mpc", "application/vnd.mpohun.certificate" },
      { ".mpe", "video/mpeg" }, { ".mpeg", "video/mpeg" }, { ".mpg", "video/mpeg" },
      { ".mpg4", "video/mp4" }, { ".mpga", "audio/mpeg" }, { ".msg", "application/vnd.ms-outlook" },
      { ".ogg", "audio/ogg" }, { ".pdf", "application/pdf" }, { ".png", "image/png" },
      { ".pps", "application/vnd.ms-powerpoint" }, { ".ppt", "application/vnd.ms-powerpoint" },
      { ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
      { ".prop", "text/plain" }, { ".rc", "text/plain" }, { ".rmvb", "audio/x-pn-realaudio" },
      { ".rtf", "application/rtf" }, { ".sh", "text/plain" }, { ".tar", "application/x-tar" },
      { ".tgz", "application/x-compressed" }, { ".txt", "text/plain" }, { ".wav", "audio/x-wav" },
      { ".wma", "audio/x-ms-wma" }, { ".wmv", "audio/x-ms-wmv" },
      { ".wps", "application/vnd.ms-works" }, { ".xml", "text/plain" },
      { ".z", "application/x-compress" }, { ".zip", "application/x-zip-compressed" }, { "", "*/*" }
  };
  public ImageView ivPictureAFourmDetail;// 图片A
  public ImageView ivPictureBFourmDetail;// 图片B
  public ImageView ivPictureCFourmDetail;// 图片C
  // private List<CompanyForumAnswer.actualObject> mAnswerDetail;
  public ImageView ivPictureDFourmDetail;// 图片D
  public TextView tvFileForumDetail; // 文件
  private DialogFragment mDialog;
  private FragmentManager mFm;
  private CompanyForumTopicAnswerListAdapter mAdapter;
  private CompanyForumTopic.actualObject mTopicContent;
  private CompanyForumAnswer.actualObject mTopicAnswer;
  private String mTopicPublisher;
  private String mTopicTitle;
  private String mTopicdetail;
  private String mTopicPublishTime;
  private String mTopicConmmentNum;
  private String mPictureA;
  private String mPictureB;
  private String mPictureC;
  private String mPictureD;
  private String mFile;
  private File mFileDownload;
  private String mfileName;
  private String mId; // 话题的id
  private String mPicture;// 头像
  private ImageLoader mImageLoader;
  private BaseVolleyActivity mActivity;
  // private int page=1;//当前页码
  private int mPage = 1;// 请求第几页的数据.
  private String mTopicPublisherId;// 话题发布人ID
  private String mCurrentUserJobNu;// 当前登录人的ID
  private String mTopicId;// 话题ID
  private String mAnseerTopicId;// 话题回复消息ID
  private String mPublishJobNo;//发布人的jobNo。
  private String mReplyJobNo;//回复人jobNO

  public static Fragment newInstance(CompanyForumTopic.actualObject topicContent) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, topicContent);
    CompanyForumTopicAnswerListFragment framgnet = new CompanyForumTopicAnswerListFragment();
    framgnet.setArguments(bundle);
    return framgnet;
  }

  @SuppressLint("DefaultLocale") private static String getMIMEType(File file) {

    String type = "*/*";
    String fName = file.getName();
    // 获取后缀名前的分隔符"."在fName中的位置。
    int dotIndex = fName.lastIndexOf(".");
    if (dotIndex < 0) {
      return type;
    }
        /* 获取文件的后缀名 */
    String end = fName.substring(dotIndex, fName.length()).toLowerCase();
    if (MyStringUtil.isEmpty(end)) return type;
    // 在MIME和文件类型的匹配表中找到对应的MIME类型。
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < MIME_MapTable.length; i++) {
      if (end.equals(MIME_MapTable[i][0])) type = MIME_MapTable[i][1];
    }
    return type;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setTitleCustom(R.string.topic);
    int[] mChoose = new int[] { R.string.answer, R.string.lookMessage, R.string.delete };
    //String reply = getResources().getString(R.string.answer);
    //String seeMessage = getResources().getString(R.string.lookMessage);

    // 初始化单选对话框.
    mDialog = BaseSingleChoiceDialogFragment.newInstance(mChoose);
    mDialog.setTargetFragment(this, REQUEST_CHOOSE);
    mFm = getActivity().getSupportFragmentManager();
    mActivity = (BaseVolleyActivity) getActivity();
    mTopicContent = (CompanyForumTopic.actualObject) getArguments().getSerializable(EXTRA_VALUE);
    if (mTopicContent != null) {
      mTopicPublisher = mTopicContent.getRegStaffName();
      mTopicTitle = mTopicContent.getTopicTitle();
      mTopicdetail = mTopicContent.getTopicContents();
      mTopicPublishTime = mTopicContent.getRegDate();
      mTopicConmmentNum = mTopicContent.getDiscussCount();
      mId = mTopicContent.getId();
      mPicture = mTopicContent.getPicture();
      mPictureA = mTopicContent.getTopicPicA();
      mPictureB = mTopicContent.getTopicPicB();
      mPictureC = mTopicContent.getTopicPicC();
      mPictureD = mTopicContent.getTopicPicD();
      mFile = mTopicContent.getTopicFile();
      mTopicPublisherId = mTopicContent.getRegStaffId();
      mTopicId = mTopicContent.getId();
      LogUtil.i("mFile/////" + mFile);
    }
    CurrentUser mCurrentUser = CurrentUser.newInstance(getActivity());
    mImageLoader = RequestManager.getImageLoader();
    mCurrentUserJobNu = mCurrentUser.getJobNumber();

    mPublishJobNo = mTopicPublisherId;
    if ((null != mTopicPublisherId) && mTopicPublisherId.contains("+")) {
      String[] resultArray = mTopicPublisherId.split("\\+");
      if (resultArray.length > 0) {
        //获取jobNO。
        mPublishJobNo = resultArray[0];
      }
    }
  }

  @Override public String getUrl() {

    return ApiConst.URL_GET_FORUM_ANSWER_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("app", "app");
    params.put("mainId", mId);
    params.put("page", mPage + "");
    params.put("rows", "20");
    params.put("orderField", "REG_DATE");
    params.put("orderSeq", "DESC");
    return params;
  }

  @Override protected String setEmptyText() {
    return getResources().getString(R.string.noMessageReply);
  }

  @Override public void resolveResponse(String arg0) {
    CompanyForumAnswer answer = new Gson().fromJson(arg0, CompanyForumAnswer.class);
    List<actualObject> answerDetail = answer.getData();
    setAdapter(answerDetail);
  }

  private void setAdapter(List<CompanyForumAnswer.actualObject> answerDetail) {
    if (answerDetail == null) {
      answerDetail = new ArrayList<>();
    }
    if (mAdapter == null) {
      mAdapter = new CompanyForumTopicAnswerListAdapter(getActivity(), answerDetail);
      setListAdapter(mAdapter);
      return;
    }

    if (mPage == 1) {
      mAdapter.clear();
    }
    mAdapter.addAll(answerDetail);
    ((CompanyForumTopicAnswerListAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mPullRefreshListView.setMode(Mode.BOTH);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_forum_topic, null, false);
    mListview.addHeaderView(header);

    RoundImageView mImageForumAnswer =
        (RoundImageView) header.findViewById(R.id.iv_image_forum_answer);
    TextView mNameForumAnswer = (TextView) header.findViewById(R.id.tv_name_forum_answer);
    TextView mTitleForumAnswer = (TextView) header.findViewById(R.id.tv_title_forum_answer);
    TextView mContentForumAnswer = (TextView) header.findViewById(R.id.tv_content_forum_answer);
    TextView mPublishTimeForumAnswer =
        (TextView) header.findViewById(R.id.tv_publishTime_forum_answer);
    TextView mForumCommentAnswer = (TextView) header.findViewById(R.id.tv_forum_comment_answer);
    ivPictureAFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureA_fourmDetail);
    ivPictureBFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureB_fourmDetail);
    ivPictureCFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureC_fourmDetail);
    ivPictureDFourmDetail = (ImageView) header.findViewById(R.id.iv_pictureD_fourmDetail);
    tvFileForumDetail = (TextView) header.findViewById(R.id.tv_file_forumDetail);

    mNameForumAnswer.setText(mTopicPublisher);
    mTitleForumAnswer.setText(mTopicTitle);
    mContentForumAnswer.setText(mTopicdetail);
    // 获取头像
    String headPicturePath = mPicture;
    if (!TextUtils.isEmpty(headPicturePath)) {
      headPicturePath = FileUtil.getThumbNailFilePath(headPicturePath);
      String urlImage = ApiConst.getDownLoadUrlByGet(headPicturePath);
      ImageListener listener = ImageLoader.getImageListener(mImageForumAnswer, // 控件名
          R.drawable.photo, R.drawable.photo); // 默认头像
      mImageLoader.get(urlImage, listener);
    }

    if ((TextUtils.isEmpty(mPictureA) && TextUtils.isEmpty(mPictureB) && TextUtils.isEmpty(
        mPictureC) && TextUtils.isEmpty(mPictureD))) {
      ivPictureAFourmDetail.setVisibility(View.GONE);
      ivPictureBFourmDetail.setVisibility(View.GONE);
      ivPictureCFourmDetail.setVisibility(View.GONE);
      ivPictureDFourmDetail.setVisibility(View.GONE);
    } else {
      // 获取图片A
      if (!TextUtils.isEmpty(mPictureA)) {
        ivPictureAFourmDetail.setVisibility(View.VISIBLE);
        //                String pictureA = FileUtil.getThumbNailFilePath(mPictureA);
        String urlImage = ApiConst.getDownLoadUrlByGet(mPictureA);
        ImageListener listener = ImageLoader.getImageListener(ivPictureAFourmDetail, // 控件名
            0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
      } else {
        ivPictureAFourmDetail.setVisibility(View.GONE);
      }
      ivPictureAFourmDetail.setOnClickListener(this);
      // 获取图片B
      if (!TextUtils.isEmpty(mPictureB)) {
        ivPictureBFourmDetail.setVisibility(View.VISIBLE);
        //                String pictureB = FileUtil.getThumbNailFilePath(mPictureB);
        String urlImage = ApiConst.getDownLoadUrlByGet(mPictureB);
        ImageListener listener = ImageLoader.getImageListener(ivPictureBFourmDetail, // 控件名
            0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
      } else {
        ivPictureBFourmDetail.setVisibility(View.GONE);
      }
      ivPictureBFourmDetail.setOnClickListener(this);

      // 获取图片C
      if (!TextUtils.isEmpty(mPictureC)) {
        ivPictureCFourmDetail.setVisibility(View.VISIBLE);
        //                String pictureC = FileUtil.getThumbNailFilePath(mPictureC);
        String urlImage = ApiConst.getDownLoadUrlByGet(mPictureC);
        ImageListener listener = ImageLoader.getImageListener(ivPictureCFourmDetail, // 控件名
            0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
      } else {
        ivPictureCFourmDetail.setVisibility(View.GONE);
      }
      ivPictureCFourmDetail.setOnClickListener(this);
      // 获取图片D
      if (!TextUtils.isEmpty(mPictureD)) {
        ivPictureDFourmDetail.setVisibility(View.VISIBLE);
        //                String pictureD = FileUtil.getThumbNailFilePath(mPictureD);
        String urlImage = ApiConst.getDownLoadUrlByGet(mPictureD);
        ImageListener listener = ImageLoader.getImageListener(ivPictureDFourmDetail, // 控件名
            0, 0); // 默认图片
        mImageLoader.get(urlImage, listener);
      } else {
        ivPictureDFourmDetail.setVisibility(View.GONE);
      }
      ivPictureDFourmDetail.setOnClickListener(this);
    }

    // 获取文件
    if (!TextUtils.isEmpty(mFile)) {
      tvFileForumDetail.setVisibility(View.VISIBLE);
      String file = mFile.substring(mFile.lastIndexOf("/") + 1, mFile.length());
      tvFileForumDetail.setText(file);
      tvFileForumDetail.setOnClickListener(this);
    }

    Date date = new Date();
    String timeDifference =
        DateUtil.dateToTimeInMillis(getActivity().getApplicationContext(), mTopicPublishTime, date);
    mPublishTimeForumAnswer.setText(timeDifference);
    mForumCommentAnswer.setText(mTopicConmmentNum);
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    // header不响应点击事件
    super.onListItemClick(l, v, position, id);
    if (position == 1 || position == 0) {
      return;
    }

    mTopicAnswer = mAdapter.getItem(position - 2);
    String mAnswerId = mTopicAnswer != null ? mTopicAnswer.getRegStaffId() : null;

    mReplyJobNo = mAnswerId;
    if ((null != mAnswerId) && mAnswerId.contains("+")) {
      String[] resultArray = mAnswerId.split("\\+");
      if (resultArray.length > 0) {
        //获取jobNO。
        mReplyJobNo = resultArray[0];
      }
    }

    mAnseerTopicId = mTopicAnswer != null ? mTopicAnswer.getId() : null;
    LogUtil.i("mAnseerTopicId=-=-=--" + mAnseerTopicId);
    // 显示对话框.
    mDialog.show(mFm, "");
  }

  /**
   * 添加回复、删除按钮
   */
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_forum_turn_reply, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  /**
   * 响应ActionBar中的按钮
   */
  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      // 响应返回按钮

      case android.R.id.home:
        getActivity().finish();
        break;

      // 响应回复按钮
      case R.id.menu_item_turn_reply:
        intent = new Intent(getActivity(), CompanyFroumTopicReplyActivity.class);
        intent.putExtra(CompanyFroumTopicReplyFragment.EXTRA_ID, mId);
        intent.putExtra(CompanyFroumTopicReplyFragment.REQUEST_TYPE,
            CompanyFroumTopicReplyFragment.VALUE_TIPIC_REPLY);
        startActivityForResult(intent, REQUEST_TOPIC_ANSWER);
        break;

      // 删除话题
      case R.id.menu_item_delete_topic:

        if (mPublishJobNo.equalsIgnoreCase(mCurrentUserJobNu)) {
          volleyDeleteTopic();
        } else {
          Toast.makeText(getActivity(), R.string.onlyPublisherDelete, Toast.LENGTH_SHORT).show();
        }
        break;

      // 话题修改
      case R.id.menu_item_edit_topic:

        if (mPublishJobNo.equalsIgnoreCase(mCurrentUserJobNu)) {
          intent = new Intent(getActivity(), CompanyForumTopicPublishActicity.class);
          if (mTopicContent != null) {
            intent.putExtra(CompanyForumTopicPublishFragment.EXTRA_VALUE, mTopicContent);
          }
          intent.putExtra(CompanyForumTopicPublishFragment.REQUEST_EDIT,
              CompanyForumTopicPublishFragment.EXTRA_EDIT_TOPIC);
          startActivityForResult(intent, RESULT_EDIT);
        } else {
          Toast.makeText(getActivity(), R.string.onlyPublisherEdit, Toast.LENGTH_SHORT).show();
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 删除前提示
   */
  private void volleyDeleteTopic() {

    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    dialog.setTitle(R.string.restart_title);
    dialog.setMessage(R.string.deleteMind);
    dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        volleyPostDelete();
      }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });

    dialog.create().show();
  }

  /**
   * 删除话题操作
   */
  protected void volleyPostDelete() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_FORUM_TOPIC);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mTopicId);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyResponse(String arg0) {
        Toast.makeText(getActivity(), R.string.deleteSuccess, Toast.LENGTH_SHORT).show();
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.deleteFail, Toast.LENGTH_SHORT).show();
        LogUtil.e("VolleyError==" + arg0);
      }
    });
  }

  /**
   * 响应对话框回复信息和查看资料点击事件
   */
  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK && (requestCode == REQUEST_TOPIC_ANSWER
        || requestCode == REQUEST_TOPIC_ANSWER_REPLY)) {
      volleyPost();
    }

    if (REQUEST_CHOOSE == requestCode && data != null) {
      // 回复信息
      int choice = data.getIntExtra(BaseSingleChoiceDialogFragment.EXTRA_RESULT, 0);
      if (choice == REQUEST_REPLY) {
        Intent replyIntent = new Intent(getActivity(), CompanyFroumTopicReplyActivity.class);
        replyIntent.putExtra(CompanyFroumTopicReplyFragment.EXTRA_ID, mId);
        replyIntent.putExtra(CompanyFroumTopicReplyFragment.EXTRA_VALUE, mTopicAnswer);
        replyIntent.putExtra(CompanyFroumTopicReplyFragment.REQUEST_TYPE,
            CompanyFroumTopicReplyFragment.VALUE_MESSAGE_REPLY);
        startActivityForResult(replyIntent, REQUEST_TOPIC_ANSWER_REPLY);
      }

      // 查看资料
      if (choice == REQUEST_MESSAGE) {
        Intent messageIntent = new Intent(getActivity(), CompanyForumPersonMessageActicity.class);
        messageIntent.putExtra(CompanyForumPersonMessageFragment.EXTRA_VALUE, mTopicAnswer);
        startActivity(messageIntent);
      }

      if (choice == REQUEST_DELETE) {
        if (!(mCurrentUserJobNu.equals(mReplyJobNo))) {
          Toast.makeText(getActivity(), R.string.onlyAnswerDelete, Toast.LENGTH_SHORT).show();
        } else {
          AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.deleteMind);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostDeleteAnswer();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });

          dialog.create().show();
        }
      }
    }

    if (requestCode == REQUEST_SHOW && data != null) {
      int choice =
          data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE, SimpleDialogFragment.VALUE_NAVIGATE);
      if (choice == SimpleDialogFragment.VALUE_POSITIVE) {
        Intent intent = getOpenFileIntent(mFileDownload);
        if (isAdded()) {
          // 用户离开当前界面,fragment在detach状态下.startActivity()会报错.
          startActivity(intent);
        }
      }
    }
    if (resultCode == Activity.RESULT_OK && requestCode == RESULT_EDIT) {
      //编辑成功,返回列表刷新.
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 删除话题回复操作
   */
  protected void volleyPostDeleteAnswer() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_FORUM_ANSWER);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mAnseerTopicId);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyResponse(String arg0) {
        Toast.makeText(getActivity(), R.string.deleteSuccess, Toast.LENGTH_SHORT).show();
        MyUtils.dismissDialog();
        volleyPost();
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.deleteFail, Toast.LENGTH_SHORT).show();
        LogUtil.e("VolleyError==" + arg0);
      }
    });
  }

  /**
   * 下拉刷新
   */
  @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) {

    Mode mode = refreshView.getCurrentMode();
    if (mode.equals(Mode.PULL_FROM_START)) {

      mPage = 1;
    }
    if (mode.equals(Mode.PULL_FROM_END)) {

      mPage++;
    }
    volleyPost();
  }

  @Override public void onClick(View v) {
    Intent intent;
    switch (v.getId()) {
      // 图片A
      case R.id.iv_pictureA_fourmDetail:
        intent = new Intent(getActivity(), CompanyForumPictureActivity.class);
        intent.putExtra(CompanyForumPictureFragment.EXTRA_PICTUREA, mPictureA);
        intent.putExtra(CompanyForumPictureFragment.TYPE, CompanyForumPictureFragment.TYPEA);
        startActivity(intent);
        break;
      // 图片B

      case R.id.iv_pictureB_fourmDetail:
        intent = new Intent(getActivity(), CompanyForumPictureActivity.class);
        intent.putExtra(CompanyForumPictureFragment.EXTRA_PICTUREB, mPictureB);
        intent.putExtra(CompanyForumPictureFragment.TYPE, CompanyForumPictureFragment.TYPEB);
        startActivity(intent);
        break;

      // 图片C
      case R.id.iv_pictureC_fourmDetail:
        intent = new Intent(getActivity(), CompanyForumPictureActivity.class);
        intent.putExtra(CompanyForumPictureFragment.EXTRA_PICTUREC, mPictureC);
        intent.putExtra(CompanyForumPictureFragment.TYPE, CompanyForumPictureFragment.TYPEC);
        startActivity(intent);
        break;

      // 图片D

      case R.id.iv_pictureD_fourmDetail:
        intent = new Intent(getActivity(), CompanyForumPictureActivity.class);
        intent.putExtra(CompanyForumPictureFragment.EXTRA_PICTURED, mPictureD);
        intent.putExtra(CompanyForumPictureFragment.TYPE, CompanyForumPictureFragment.TYPED);
        startActivity(intent);
        break;

      // 文件
      case R.id.tv_file_forumDetail:
        mfileName = mFile.substring(mFile.lastIndexOf("/") + 1, mFile.length());
        if (!TextUtils.isEmpty(mfileName)) {
          mFileDownload = new File(FileUtil.getFileDir(), mfileName);
          if (!mFileDownload.getParentFile().exists()) {
            //noinspection ResultOfMethodCallIgnored
            mFileDownload.getParentFile().mkdirs();
          }
          if (!mFileDownload.exists()) {
            AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getActivity());
            pictureDialog.setMessage(R.string.sureDownload);
            pictureDialog.setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {

                  @Override public void onClick(DialogInterface dialog, int which) {
                    new FileNetWorkUtil(getActivity()).downLoadFile(mFile, mfileName,
                        new DownLoadHandler(mFileDownload));
                  }
                });

            pictureDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
              }
            });
            pictureDialog.create().show();
          } else {
            showDialog(REQUEST_SHOW);
          }
        }
        break;

      default:
        break;
    }
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      case REQUEST_SHOW:
        dialog = SimpleDialogFragment.newInstance(R.string.alreadyDownload, R.string.show, 0,
            android.R.string.cancel);
        break;
      case REQUEST_DOWNLOAD:
        dialog = SimpleDialogFragment.newInstance(R.string.haveNotDownload, R.string.download, 0,
            android.R.string.cancel);
        break;
      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog == null) return;
    dialog.setTargetFragment(CompanyForumTopicAnswerListFragment.this, requestCode);
    dialog.show(fm, "");
  }

  protected Intent getOpenFileIntent(File file) {
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Intent.ACTION_VIEW);
    String type = getMIMEType(file);
    intent.setDataAndType(Uri.fromFile(file), type);
    return intent;
  }

  @SuppressWarnings("deprecation") private class DownLoadHandler
      extends FileAsyncHttpResponseHandler {

    DownLoadHandler(File file) {
      super(file);
    }

    @Override public void onStart() {

      Toast.makeText(getActivity(), R.string.isDownLoading, Toast.LENGTH_SHORT).show();
    }

    @Override public void onProgress(long bytesWritten, long totalSize) {

    }

    @Override public void onSuccess(int statusCode, Header[] headers, File response) {

      Intent intent = getOpenFileIntent(mFileDownload);
      if (isAdded()) {
        // 用户离开当前界面,fragment在detach状态下.startActivity()会报错.
        startActivity(intent);
      }
    }

    @Override public void onFailure(int arg0, Header[] arg1, Throwable arg2, File arg3) {
      MyUtils.dismissDialog();
      Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_SHORT).show();
      LogUtil.i(TAG, "responseError=" + arg0 + arg2 + arg3);
    }
  }
}
